<template>
  <div class="child">
    <div>子组件</div>
    <h1>{{ childData }}</h1>

    <div class="button" @click="updateData">2、emit 子组件更新父组件数据</div>

    <div class="button" style="margin-top: 10px" @click="mitEmitMessage">
      5、eventBus传值
    </div>
    <otherComponent />
  </div>
</template>

<script setup lang="ts">
import {ref,provide} from "vue"
import { getCurrentInstance } from "vue";
import otherComponent from "./otherComponent.vue";

// 1、props
//向父组件暴露属性
// const props = defineProps({
//   childData: {
//     type: String,
//     default: "",
//   },
// });

//增强类型定义
const props = defineProps<{
  childData: String;
}>();

// 2、emit
const emits = defineEmits(["updateData"]);
const updateData = () => {
  emits("updateData", "data from child");
};

// const parentData = ref("123");

//3、通过refs访问子组件方法和属性
let message = ref("我是子元素").value;
const alertMessage = function () {
  alert(message);
};
defineExpose({
  message,
  alertMessage,
});

//4、provide/inject
const middleProperty = ref(2);
provide("middleData", middleProperty);
setTimeout(() => {
  middleProperty.value = 3;
}, 2000);

//5、eventBus传值
const instance = getCurrentInstance();
function mitEmitMessage() {
  instance?.proxy?.$Bus.emit("message", 12);
}
</script>

<style scoped>
.child {
  background-color: aquamarine;
  border-radius: 20px;
  width: 300px;
  height: auto;
  margin: auto;
  padding: 20px;
}
.button {
  background-color: #4caf50; /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  border-radius: 10px;
}
</style>
